using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Data;

namespace Dbam.DbFramework.Tests
{
	[TestFixture]
	public class ORMTests
	{
		private IDbFactory _dbFactory;

		[SetUp]
		public void Setup()
		{
			_dbFactory = new SqlDbFactory(TestSettings.Default.DbSampleConnectionString);
			_dbFactory.CreateCommand("delete from [Accounts] where 1=1").ExecuteNonQuery();
		}

		[Test]
		public void InsertUpdateTest()
		{
			ObjectRelationalMapper<AccountEntity> orm = new ObjectRelationalMapper<AccountEntity>(_dbFactory);
			AccountEntity account = new AccountEntity();
			account.AccountId = Guid.NewGuid();
			account.Name = "Test Account";
			account.OpenDate = DateTime.Parse("1/2/3456");
			account.LastLogon = null;
			orm.Insert(account);
			account.Name = "Test Account (Updated)";
			orm.Update(account);
		}

		[Test]
		public void GetFromTableTest()
		{
			ObjectRelationalMapper<AccountEntity> orm = new ObjectRelationalMapper<AccountEntity>(_dbFactory);
			for(int index = 0; index < 10; index++)
			{
				AccountEntity account = new AccountEntity();
				account.Name = string.Format("Test Account {0}", index);
				account.AccountId = Guid.NewGuid();
				account.LastLogon = null;
				account.OpenDate = DateTime.Now;
				orm.Insert(account);
			}

			DataTable table = _dbFactory.ExecuteDataTable("Accounts", "", "[Name] ASC");
			AccountEntity[] accounts = orm.LoadFromTable(table);

			Assert.AreEqual(10, accounts.Length);
			for(int index = 0; index < 10; index++)
				Assert.AreEqual(string.Format("Test Account {0}", index), accounts[index].Name);
		}

		[Test]
		public void UpdateDbUsingTableTest()
		{
			ObjectRelationalMapper<AccountEntity> orm = new ObjectRelationalMapper<AccountEntity>(_dbFactory);
			List<AccountEntity> accounts = new List<AccountEntity>();
			for(int index = 0; index < 10; index++)
			{
				AccountEntity account = new AccountEntity();
				account.Name = string.Format("Test Account {0}", index);
				account.AccountId = Guid.NewGuid();
				account.LastLogon = null;
				account.OpenDate = DateTime.Now;
				orm.Insert(account);
				accounts.Add(account);
			}

			DataTable table = orm.GetTable(accounts);
			table.Rows[0]["Id"] = new Guid();
			orm.UpdateTable(table);
		}
	}
}